package com.tsd.system.service.impl;

import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.PageBean;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.dao.SysGroupMapper;
import com.tsd.system.dao.SysRoleMapper;
import com.tsd.system.dao.SysUserMapper;
import com.tsd.system.dao.SysUserRoleMapper;
import com.tsd.system.entity.*;
import com.tsd.system.service.SysUserResourceService;
import com.tsd.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述：SysUserRole 服务实现层
 *
 * @author Hillpool
 * @date 2019/03/12 12:20:51
 */
@Service
public class SysUserRoleServiceImpl extends BaseServiceImpl implements SysUserRoleService {

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysGroupMapper sysGroupMapper;

    private final SysUserResourceService sysUserResourceService;

    @Autowired
    public SysUserRoleServiceImpl(SysUserResourceService sysUserResourceService) {
        this.sysUserResourceService = sysUserResourceService;
    }

    @Override
    public SysUserRole getSysUserRoleById(Long id) throws Exception {
        return sysUserRoleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveSysUserRole(SysUserRole record, SysUser sysUser) throws Exception {
        super.checkEmpty(record.getUser_sid(), "缺少用户id");
        super.checkEmpty(record.getRole_sid(), "缺少角色id");
        Map<String, Object> params = new HashMap<>();
        params.put("userSid", record.getUser_sid());
        params.put("roleSid", record.getRole_sid());
        List<SysUserRoleExt> olds = findRoleListByUserId(params);
        boolean isSame = false;
        if (olds != null && !olds.isEmpty()) {
            if (!olds.get(0).getRole_sid().equals(record.getRole_sid())) {
                sysUserResourceService.deleteSysUserResource(sysUser, record.getUser_sid());
                for (SysUserRole userRole : olds) {
                    deleteLogicalUserRoleById(userRole.getId(), sysUser);
                }
            } else {
                isSame = true;
            }
        }
        if (!isSame) {
            SysRole role = sysRoleMapper.selectBySid(record.getRole_sid());
            super.checkEmpty(role, "角色不存在");
            SysUser user = sysUserMapper.selectBySid(record.getUser_sid());
            super.checkEmpty(user, "用户不存在");
            super.autoInjectBaseData(record, sysUser, TYPE_CREATE);
            record.setSync_user_resource(1);
            sysUserRoleMapper.insertSelective(record);
            sysUserResourceService.updateFromInheritedByUserRole();//只有第一次设置角色才,
        }
    }

    @Override
    public void deleteSysUserRole(Long id) throws Exception {
        sysUserRoleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<SysUserRole> findSysUserRoles(Map<String, Object> params, PageBean page) throws Exception {
        return sysUserRoleMapper.selectByPage(params, page);
    }

    @Override
    public void saveRoleList2User(String userId, List<String> roleIdList, boolean overwrite, SysUser opUser) throws Exception {
        SysUser user = sysUserMapper.selectBySid(userId);
        super.checkEmpty(user, "userid不存在：" + userId);
        Map<String, Object> params = new HashMap<>();
        params.put("userSid", userId);
        List<SysUserRoleExt> oldList = sysUserRoleMapper.selectByUserSid(params);
        if (overwrite) {
            //覆盖模式，将原有不存在的逻辑删除
            List<SysUserRole> dels = new ArrayList<>();
            for (SysUserRole t : oldList) {
                boolean has = false;
                for (String id : roleIdList) {
                    if (id.equals(t.getRole_sid())) {
                        has = true;
                        break;
                    }
                }
                if (!has) {
                    dels.add(t);
                }
            }
            for (SysUserRole t : dels) {
                sysUserRoleMapper.deleteByPrimaryKey(t.getId());
            }
            oldList.removeAll(dels);
        }
        for (String id : roleIdList) {
            boolean hasDone = false;
            for (SysUserRole t : oldList) {
                if (id.equals(t.getRole_sid())) {
                    //已经存在，这个跳出，如果原来是删除状态，则进行恢复
                    if (t.getDr() != null && t.getDr() == 1) {
                        t.setDr(0);
                        t.setUpdate_date(new Date());
                    }
                    t.setSync_user_resource(1);
                    sysUserRoleMapper.updateByPrimaryKeySelective(t);
                    hasDone = true;
                    break;
                }
            }
            if (hasDone) {
                continue;
            }
            SysRole role = sysRoleMapper.selectBySid(id);
            if (role == null) {
                throw new HlpException("找不到对应的角色信息:" + id);
            }
            SysUserRole t = new SysUserRole();
            t.setRole_sid(id);
            t.setUser_sid(userId);
            t.setSync_user_resource(1);
            saveSysUserRole(t, opUser);
        }
        sysUserResourceService.updateFromInheritedByUserRole();
    }

    @Override
    public void deleteLogicalUserRoleById(Long id, SysUser sysUser) throws Exception {
        SysUserRole t = sysUserRoleMapper.selectByPrimaryKey(id);
        super.autoInjectBaseData(t, sysUser, TYPE_DELETE);
        t.setSync_user_resource(1);
        sysUserRoleMapper.deleteLogicalByPrimaryKey(t);
        sysUserResourceService.updateFromInheritedByUserRole();
    }

    @Override
    public List<SysUserRoleExt> findRoleListByUserId(Map<String, Object> params) throws Exception {
        List<SysUserRoleExt> sysUserRoleExts = sysUserRoleMapper.selectByUserSid(params);
        SysUser sysUser = sysUserMapper.selectBySid((String) params.get("userSid"));
        SysGroup sysGroup = null;
        if (sysUser != null) {
            if (!HlpUtils.isEmpty(sysUser.getGroup_sid())) {
                sysGroup = sysGroupMapper.selectBySid(sysUser.getGroup_sid());
            }
        }
        if (!HlpUtils.isEmptyList(sysUserRoleExts)) {
            for (SysUserRoleExt sysUserRole : sysUserRoleExts) {
                SysRole sysRole = sysRoleMapper.selectBySid(sysUserRole.getRole_parent_sid());
                sysUserRole.setSysRole(sysRole);
                sysUserRole.setSysGroup(sysGroup);
            }
        }
        return sysUserRoleExts;
    }

    @Override
    public List<SysUserRoleExt> findByUserId(String userSid) throws Exception {
        Map<String, Object> params = new HashMap<>(1);
        params.put("userSid", userSid);
        return sysUserRoleMapper.selectByUserSid(params);
    }
}
